package com.payment.controller.payment;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.payment.entity.payment.paypalpay.request.RequestPaypalPay;
import com.payment.entity.payment.paypalpay.request.RequestPaypalPayData;
import com.payment.entity.payment.paypalpay.request.RequestPaypalPayTradeData;
import com.payment.entity.payment.paypalpay.response.ResponsePaypalPay;
import com.payment.entity.payment.paypalpay.response.ResponsePaypalPayData;
import com.payment.entity.payment.paypalpay.response.ResponsePaypalPayTradeData;
import com.payment.service.SequenceService;
import com.payment.utils.MD5;
import com.payment.utils.UtilsInterfacesPackage;
import com.payment.utils.payment.PayPalConstants;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import io.swagger.annotations.ApiParam;
import org.apache.commons.lang3.StringUtils;
import org.apache.log4j.Logger;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.text.SimpleDateFormat;
import java.util.Date;

@RestController
@Api(description = "PAYPAL支付")
/**
 * 1，使用领科的paypal收款接口，Paypal支付接口：
 *
 * 2，适用于新的客户：最新版的的领科 H5 和其他想要使用领科收款接口收款的（可以是客户自己的账号或者领科发账号）客户；
 *
 * 3，更新的数据表为：user_order_package_t，user_order_payment_t；
 *
 * 4，更新的数据库为：v-shop
 *
 * @author lm
 * @date 2019/11/06
 */
public class PaypalPayController {
    private static Logger logger = Logger.getLogger(PaypalPayController.class);
    @Autowired
    private SequenceService sequenceService;

    /***PAYPAL支付付款接口
     *
     * @param requestPaypalPay
     * @param
     * @return
     * @throws Exception
     */
    @PostMapping(value = "/paypal", produces = "application/json;charset=utf-8")
    @CrossOrigin
    @ResponseBody
    @ApiOperation(value = "PAYPAL支付", response = ResponsePaypalPay.class)
    public String paypal(@ApiParam @RequestBody RequestPaypalPay requestPaypalPay) throws Exception {
        // 1，生成流水号
        String connSeqNo = sequenceService.getPackageTaskNo();
        // 2,生成当前时间戳
        SimpleDateFormat df = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        String curtime = df.format(new Date());
        //3，定义回报报文
        String jsonString;
        UtilsInterfacesPackage utils = new UtilsInterfacesPackage();

        String requestStr = JSON.toJSONString(requestPaypalPay);
        if (requestStr == null) {
            logger.info("请求报文不合法:requestStr为空");
            jsonString = utils.dataWeiKong(connSeqNo, curtime);
            return jsonString;
        } else {
            logger.info("前端请求报文是：" + requestStr);
            RequestPaypalPay requestPackage = JSONArray.parseObject(requestStr, RequestPaypalPay.class);
            String requestSign = requestPackage.getSign();
            if (requestSign == null) {
                logger.info("请求报文不合法:sign为空");
                jsonString = utils.dataWeiKong(connSeqNo, curtime);
                return jsonString;
            } else {
                logger.info("请求的签名是：" + requestSign);
                RequestPaypalPayData requestData = requestPackage.getData();
                if (requestData == null) {
                    logger.info("请求报文不合法:data为空");
                    jsonString = utils.dataWeiKong(connSeqNo, curtime);
                    return jsonString;
                } else {
                    String partnerCode = requestData.getPartnerCode();
                    String ConnSeqNo = requestData.getConnSeqNo();
                    String tradeTime = requestData.getTradeTime();
                    String tradeType = requestData.getTradeType();
                    String lang = requestData.getLang();
                    String version = requestData.getVersion();

                    RequestPaypalPayTradeData requestTradeData = requestData.getTradeData();

                    if (requestTradeData == null || StringUtils.isBlank(partnerCode) || StringUtils.isBlank(ConnSeqNo) || StringUtils.isBlank(tradeTime) || StringUtils.isBlank(tradeType) || lang == null || version == null) {
                        logger.info("请求报文不合法:data参数不合法");
                        jsonString = utils.dataWeiKong(connSeqNo, curtime);
                        return jsonString;
                    } else {

                        String payAmount = requestTradeData.getPayAmount();
                        String payId = requestTradeData.getPayId();
                        String mode = requestTradeData.getMode();
                        String clientId = requestTradeData.getClientId();
                        String clientSecret = requestTradeData.getClientSecret();

                        if (StringUtils.isBlank(payAmount) || StringUtils.isBlank(payId) || StringUtils.isBlank(mode) || clientId == null || clientSecret == null) {
                            logger.info("请求报文不合法:payAmount和payId不可以为空！");
                            jsonString = utils.dataWeiKong(connSeqNo, curtime);
                            return jsonString;
                        } else {
                            // 将请求体json转成String
                            String str = JSON.toJSONString(requestData);
                            // 将Str拿去计算签名
                            String sign = utils.calculateSignature(str);
                            logger.info("计算的签名是：" + sign);
                            if (!requestSign.equalsIgnoreCase(sign)) {
                                logger.info("签名验证失败！");
                                jsonString = utils.signatureFailure(ConnSeqNo, tradeTime, partnerCode, tradeType);
                                return jsonString;
                            } else {
                                boolean b1 = (StringUtils.isBlank(clientId) || StringUtils.isBlank(clientSecret)) && mode.equals("sandbox");

                                boolean b2 = (StringUtils.isBlank(clientId) || StringUtils.isBlank(clientSecret)) && mode.equals("production");

                                ResponsePaypalPayTradeData tradeData = new ResponsePaypalPayTradeData();
                                tradeData.setPayId(payId);

                                //玖零皓 (P000609:老业务；P000818：新业务)

                                if (partnerCode.equalsIgnoreCase("P000609") || partnerCode.equalsIgnoreCase("P000818")) {
                                    //对某个客户做特殊的处理
                                    if (b1) {
                                        //领科账号sandbox环境
                                        String CLINENTID = PayPalConstants.sanbox_ClientId_P000609;
                                        String CLINTSECRET = PayPalConstants.sanbox_ClientSecret_P000609;
                                        String MODE = "sandbox";

                                        tradeData.setMode(MODE);
                                        tradeData.setClientId(CLINENTID);
                                        tradeData.setClientSecret(CLINTSECRET);

                                    } else if (b2) {
                                        //领科账号production环境
                                        String CLINENTID = PayPalConstants.production_ClientId_P000609;
                                        String CLINTSECRET = PayPalConstants.production_ClientSecret_P000609;
                                        String MODE = "production";

                                        tradeData.setMode(MODE);
                                        tradeData.setClientId(CLINENTID);
                                        tradeData.setClientSecret(CLINTSECRET);

                                    } else {
                                        //接口带上来的客户自己的账号
                                        tradeData.setMode(mode);
                                        tradeData.setClientId(clientId);
                                        tradeData.setClientSecret(clientSecret);
                                    }


                                } else if (partnerCode.equalsIgnoreCase("P000359")) {
                                    //对尔登做特殊的处理
                                    if (b1) {
                                        //领科账号sandbox环境
                                        String CLINENTID = PayPalConstants.sanbox_ClientId_P000359;
                                        String CLINTSECRET = PayPalConstants.sanbox_ClientSecret_P000359;
                                        String MODE = "sandbox";

                                        tradeData.setMode(MODE);
                                        tradeData.setClientId(CLINENTID);
                                        tradeData.setClientSecret(CLINTSECRET);

                                    } else if (b2) {
                                        //领科账号production环境
                                        String CLINENTID = PayPalConstants.production_ClientId_P000359;
                                        String CLINTSECRET = PayPalConstants.production_ClientSecret_P000359;
                                        String MODE = "production";


                                        tradeData.setMode(MODE);
                                        tradeData.setClientId(CLINENTID);
                                        tradeData.setClientSecret(CLINTSECRET);

                                    } else {
                                        //接口带上来的客户自己的账号
                                        tradeData.setMode(mode);
                                        tradeData.setClientId(clientId);
                                        tradeData.setClientSecret(clientSecret);
                                    }


                                } else if (partnerCode.equalsIgnoreCase("P000906")) {
                                    //对苏钠米做特殊的处理
                                    if (b1) {
                                        //领科账号sandbox环境
                                        String CLINENTID = PayPalConstants.sanbox_ClientId_P000906;
                                        String CLINTSECRET = PayPalConstants.sanbox_ClientSecret_P000906;
                                        String MODE = "sandbox";

                                        tradeData.setMode(MODE);
                                        tradeData.setClientId(CLINENTID);
                                        tradeData.setClientSecret(CLINTSECRET);

                                    } else if (b2) {
                                        //领科账号production环境
                                        String CLINENTID = PayPalConstants.production_ClientId_P000906;
                                        String CLINTSECRET = PayPalConstants.production_ClientSecret_P000906;
                                        String MODE = "production";


                                        tradeData.setMode(MODE);
                                        tradeData.setClientId(CLINENTID);
                                        tradeData.setClientSecret(CLINTSECRET);

                                    } else {
                                        //接口带上来的客户自己的账号
                                        tradeData.setMode(mode);
                                        tradeData.setClientId(clientId);
                                        tradeData.setClientSecret(clientSecret);
                                    }


                                } else if (partnerCode.equalsIgnoreCase("P000242")) {
                                    //启越特殊自己收款
                                    if (b1) {
                                        //启越账号sandbox环境
                                        String CLINENTID = PayPalConstants.sanbox_ClientId_P000242;
                                        String CLINTSECRET = PayPalConstants.sanbox_ClientSecret_P000242;
                                        String MODE = "sandbox";

                                        tradeData.setMode(MODE);
                                        tradeData.setClientId(CLINENTID);
                                        tradeData.setClientSecret(CLINTSECRET);

                                    } else if (b2) {
                                        //启越账号production环境
                                        String CLINENTID = PayPalConstants.production_ClientId_P000242;
                                        String CLINTSECRET = PayPalConstants.production_ClientSecret_P000242;
                                        String MODE = "production";

                                        tradeData.setMode(MODE);
                                        tradeData.setClientId(CLINENTID);
                                        tradeData.setClientSecret(CLINTSECRET);

                                    } else {
                                        //接口带上来的客户自己的账号
                                        tradeData.setMode(mode);
                                        tradeData.setClientId(clientId);
                                        tradeData.setClientSecret(clientSecret);
                                    }

                                } else {//默认走领科的账号收款
                                    if (b1) {
                                        //领科账号sandbox环境
                                        String CLINENTID = PayPalConstants.sanbox_ClientId;
                                        String CLINTSECRET = PayPalConstants.sanbox_ClientSecret;
                                        String MODE = "sandbox";

                                        tradeData.setMode(MODE);
                                        tradeData.setClientId(CLINENTID);
                                        tradeData.setClientSecret(CLINTSECRET);

                                    } else if (b2) {
                                        //领科账号production环境
                                        String CLINENTID = PayPalConstants.production_ClientId;
                                        String CLINTSECRET = PayPalConstants.production_ClientSecret;
                                        String MODE = "production";

                                        tradeData.setMode(MODE);
                                        tradeData.setClientId(CLINENTID);
                                        tradeData.setClientSecret(CLINTSECRET);

                                    } else {
                                        //接口带上来的客户自己的账号
                                        tradeData.setMode(mode);
                                        tradeData.setClientId(clientId);
                                        tradeData.setClientSecret(clientSecret);
                                    }
                                }

                                ResponsePaypalPayData data = new ResponsePaypalPayData();
                                data.setConnSeqNo(ConnSeqNo);
                                data.setPartnerCode(partnerCode);
                                data.setTradeType(tradeType);
                                data.setTradeTime(tradeTime);
                                data.setTradeRstCode("0000");
                                if (lang.equals("cn") || StringUtils.isBlank(lang)) {
                                    data.setTradeRstMessage("成功");
                                } else {
                                    data.setTradeRstMessage("success");
                                }
                                data.setTradeData(tradeData);

                                ResponsePaypalPay responsePaypalPay = new ResponsePaypalPay();
                                responsePaypalPay.setData(data);
                                responsePaypalPay.setSign(MD5.calcMD5(JSON.toJSONString(data)));
                                // 返回给调用者的报文
                                jsonString = JSON.toJSONString(responsePaypalPay);
                                logger.info("响应报文：" + jsonString);
                                return jsonString;

                            }
                        }
                    }
                }
            }
        }
    }
}
